<template>
  <div class="apple-table-container" :class="containerClass">
    <!-- 表格工具栏 -->
    <div v-if="showToolbar" class="apple-table__toolbar">
      <div class="apple-table__toolbar-left">
        <slot name="toolbar-left">
          <h3 v-if="title" class="apple-table__title">{{ title }}</h3>
        </slot>
      </div>
      <div class="apple-table__toolbar-right">
        <slot name="toolbar-right">
          <!-- 搜索框 -->
          <AppleInput
            v-if="searchable"
            v-model="searchValue"
            placeholder="搜索..."
            prefix-icon="search"
            clearable
            class="apple-table__search"
          />
          <!-- 刷新按钮 -->
          <AppleButton
            v-if="refreshable"
            variant="secondary"
            size="small"
            @click="handleRefresh"
            :loading="refreshing"
          >
            刷新
          </AppleButton>
        </slot>
      </div>
    </div>

    <!-- 表格主体 -->
    <div class="apple-table__wrapper" :style="wrapperStyle">
      <table class="apple-table" :class="tableClass">
        <!-- 表头 -->
        <thead class="apple-table__header">
          <tr>
            <!-- 选择列 -->
            <th v-if="selectable" class="apple-table__cell apple-table__cell--selection">
              <input
                type="checkbox"
                class="apple-table__checkbox"
                :checked="isAllSelected"
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
              />
            </th>
            <!-- 数据列 -->
            <th
              v-for="column in visibleColumns"
              :key="column.prop"
              class="apple-table__cell"
              :class="getColumnClass(column)"
              :style="getColumnStyle(column)"
              @click="handleSort(column)"
            >
              <div class="apple-table__cell-content">
                <span class="apple-table__cell-text">
                  {{ column.label }}
                </span>
                <span
                  v-if="column.sortable"
                  class="apple-table__sort-icon"
                  :class="getSortIconClass(column)"
                >
                  <svg viewBox="0 0 12 12" fill="currentColor">
                    <path d="M6 2L9 7H3L6 2Z" />
                  </svg>
                </span>
              </div>
            </th>
          </tr>
        </thead>

        <!-- 表体 -->
        <tbody class="apple-table__body">
          <template v-if="!loading && displayData.length > 0">
            <tr
              v-for="(row, rowIndex) in displayData"
              :key="getRowKey(row, rowIndex)"
              class="apple-table__row"
              :class="getRowClass(row, rowIndex)"
              @click="handleRowClick(row, rowIndex)"
            >
              <!-- 选择列 -->
              <td v-if="selectable" class="apple-table__cell apple-table__cell--selection">
                <input
                  type="checkbox"
                  class="apple-table__checkbox"
                  :checked="isRowSelected(row)"
                  @change="handleRowSelect(row, $event)"
                  @click.stop
                />
              </td>
              <!-- 数据列 -->
              <td
                v-for="column in visibleColumns"
                :key="column.prop"
                class="apple-table__cell"
                :class="getColumnClass(column)"
                :style="getColumnStyle(column)"
              >
                <div class="apple-table__cell-content">
                  <slot
                    :name="column.prop"
                    :row="row"
                    :column="column"
                    :index="rowIndex"
                    :value="getCellValue(row, column.prop)"
                  >
                    <span class="apple-table__cell-text">
                      {{ formatCellValue(getCellValue(row, column.prop), column) }}
                    </span>
                  </slot>
                </div>
              </td>
            </tr>
          </template>

          <!-- 空状态 -->
          <tr v-else-if="!loading && displayData.length === 0" class="apple-table__empty">
            <td :colspan="totalColumns" class="apple-table__cell">
              <div class="apple-table__empty-content">
                <slot name="empty">
                  <div class="apple-table__empty-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                      <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                      <line x1="16" y1="2" x2="16" y2="6"/>
                      <line x1="8" y1="2" x2="8" y2="6"/>
                      <line x1="3" y1="10" x2="21" y2="10"/>
                    </svg>
                  </div>
                  <p class="apple-table__empty-text">{{ emptyText }}</p>
                </slot>
              </div>
            </td>
          </tr>

          <!-- 加载状态 -->
          <tr v-else-if="loading" class="apple-table__loading">
            <td :colspan="totalColumns" class="apple-table__cell">
              <div class="apple-table__loading-content">
                <div class="apple-table__loading-spinner"></div>
                <p class="apple-table__loading-text">{{ loadingText }}</p>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页器 -->
    <div v-if="showPagination && pagination" class="apple-table__pagination">
      <div class="apple-table__pagination-info">
        显示第 {{ (pagination.current - 1) * pagination.pageSize + 1 }} - 
        {{ Math.min(pagination.current * pagination.pageSize, pagination.total) }} 条，
        共 {{ pagination.total }} 条
      </div>
      <div class="apple-table__pagination-controls">
        <AppleButton
          variant="secondary"
          size="small"
          :disabled="pagination.current <= 1"
          @click="handlePageChange(pagination.current - 1)"
        >
          上一页
        </AppleButton>
        <span class="apple-table__pagination-current">
          第 {{ pagination.current }} / {{ totalPages }} 页
        </span>
        <AppleButton
          variant="secondary"
          size="small"
          :disabled="pagination.current >= totalPages"
          @click="handlePageChange(pagination.current + 1)"
        >
          下一页
        </AppleButton>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import AppleButton from './AppleButton.vue'
import AppleInput from './AppleInput.vue'

export interface TableColumn {
  prop: string
  label: string
  width?: string | number
  minWidth?: string | number
  align?: 'left' | 'center' | 'right'
  sortable?: boolean
  formatter?: (value: any, row: any) => string
  className?: string
  fixed?: boolean
}

export interface TablePagination {
  current: number
  pageSize: number
  total: number
}

export interface AppleTableProps {
  data: any[]
  columns: TableColumn[]
  loading?: boolean
  selectable?: boolean
  selection?: any[]
  rowKey?: string | ((row: any) => string)
  stripe?: boolean
  border?: boolean
  size?: 'small' | 'medium' | 'large'
  maxHeight?: string | number
  height?: string | number
  title?: string
  emptyText?: string
  loadingText?: string
  searchable?: boolean
  refreshable?: boolean
  showToolbar?: boolean
  showPagination?: boolean
  pagination?: TablePagination
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
  customClass?: string
}

const props = withDefaults(defineProps<AppleTableProps>(), {
  data: () => [],
  columns: () => [],
  loading: false,
  selectable: false,
  selection: () => [],
  stripe: true,
  border: false,
  size: 'medium',
  title: '',
  emptyText: '暂无数据',
  loadingText: '加载中...',
  searchable: false,
  refreshable: false,
  showToolbar: true,
  showPagination: true,
  sortOrder: 'asc',
  customClass: ''
})

const emit = defineEmits<{
  'selection-change': [selection: any[]]
  'row-click': [row: any, index: number]
  'sort-change': [prop: string, order: 'asc' | 'desc' | null]
  'page-change': [page: number]
  'refresh': []
  'search': [keyword: string]
}>()

// 内部状态
const searchValue = ref('')
const refreshing = ref(false)
const currentSort = ref({ prop: props.sortBy || '', order: props.sortOrder })
const internalSelection = ref<any[]>([...props.selection])

// 计算属性
const visibleColumns = computed(() => props.columns.filter(col => col.prop))

const totalColumns = computed(() => {
  let count = visibleColumns.value.length
  if (props.selectable) count++
  return count
})

const containerClass = computed(() => [
  `apple-table-container--${props.size}`,
  {
    'apple-table-container--border': props.border,
    'apple-table-container--stripe': props.stripe,
  },
  props.customClass
])

const tableClass = computed(() => [
  `apple-table--${props.size}`,
  {
    'apple-table--border': props.border,
    'apple-table--stripe': props.stripe,
  }
])

const wrapperStyle = computed(() => {
  const style: Record<string, string> = {}
  if (props.height) {
    style.height = typeof props.height === 'number' ? `${props.height}px` : props.height
  }
  if (props.maxHeight) {
    style.maxHeight = typeof props.maxHeight === 'number' ? `${props.maxHeight}px` : props.maxHeight
  }
  return style
})

// 搜索和筛选后的数据
const filteredData = computed(() => {
  if (!searchValue.value) return props.data
  
  const keyword = searchValue.value.toLowerCase()
  return props.data.filter(row => {
    return visibleColumns.value.some(column => {
      const value = getCellValue(row, column.prop)
      return String(value).toLowerCase().includes(keyword)
    })
  })
})

// 排序后的数据
const sortedData = computed(() => {
  if (!currentSort.value.prop || !currentSort.value.order) {
    return filteredData.value
  }

  const { prop, order } = currentSort.value
  return [...filteredData.value].sort((a, b) => {
    const aVal = getCellValue(a, prop)
    const bVal = getCellValue(b, prop)
    
    let result = 0
    if (aVal < bVal) result = -1
    else if (aVal > bVal) result = 1
    
    return order === 'desc' ? -result : result
  })
})

// 最终显示的数据
const displayData = computed(() => sortedData.value)

// 分页相关
const totalPages = computed(() => {
  if (!props.pagination) return 1
  return Math.ceil(props.pagination.total / props.pagination.pageSize)
})

// 选择相关
const isAllSelected = computed(() => {
  return displayData.value.length > 0 && 
         displayData.value.every(row => isRowSelected(row))
})

const isIndeterminate = computed(() => {
  const selectedCount = displayData.value.filter(row => isRowSelected(row)).length
  return selectedCount > 0 && selectedCount < displayData.value.length
})

// 工具函数
const getRowKey = (row: any, index: number) => {
  if (typeof props.rowKey === 'function') {
    return props.rowKey(row)
  }
  return props.rowKey ? row[props.rowKey] : index
}

const getCellValue = (row: any, prop: string) => {
  const keys = prop.split('.')
  let value = row
  for (const key of keys) {
    value = value?.[key]
  }
  return value
}

const formatCellValue = (value: any, column: TableColumn) => {
  if (column.formatter) {
    return column.formatter(value, {})
  }
  return value ?? ''
}

const getColumnClass = (column: TableColumn) => [
  `apple-table__cell--${column.align || 'left'}`,
  {
    'apple-table__cell--sortable': column.sortable,
    'apple-table__cell--fixed': column.fixed,
  },
  column.className
]

const getColumnStyle = (column: TableColumn) => {
  const style: Record<string, string> = {}
  if (column.width) {
    style.width = typeof column.width === 'number' ? `${column.width}px` : column.width
  }
  if (column.minWidth) {
    style.minWidth = typeof column.minWidth === 'number' ? `${column.minWidth}px` : column.minWidth
  }
  return style
}

const getRowClass = (row: any, index: number) => [
  {
    'apple-table__row--selected': isRowSelected(row),
    'apple-table__row--stripe': props.stripe && index % 2 === 1,
  }
]

const getSortIconClass = (column: TableColumn) => [
  'apple-table__sort-icon',
  {
    'apple-table__sort-icon--asc': currentSort.value.prop === column.prop && currentSort.value.order === 'asc',
    'apple-table__sort-icon--desc': currentSort.value.prop === column.prop && currentSort.value.order === 'desc',
  }
]

const isRowSelected = (row: any) => {
  const key = getRowKey(row, 0)
  return internalSelection.value.some(item => getRowKey(item, 0) === key)
}

// 事件处理
const handleSort = (column: TableColumn) => {
  if (!column.sortable) return
  
  let order: 'asc' | 'desc' | null = 'asc'
  
  if (currentSort.value.prop === column.prop) {
    if (currentSort.value.order === 'asc') {
      order = 'desc'
    } else if (currentSort.value.order === 'desc') {
      order = null
    }
  }
  
  currentSort.value = {
    prop: order ? column.prop : '',
    order: order || 'asc'
  }
  
  emit('sort-change', column.prop, order)
}

const handleSelectAll = (event: Event) => {
  const checked = (event.target as HTMLInputElement).checked
  if (checked) {
    internalSelection.value = [...displayData.value]
  } else {
    internalSelection.value = []
  }
  emit('selection-change', internalSelection.value)
}

const handleRowSelect = (row: any, event: Event) => {
  const checked = (event.target as HTMLInputElement).checked
  const key = getRowKey(row, 0)
  
  if (checked) {
    if (!isRowSelected(row)) {
      internalSelection.value.push(row)
    }
  } else {
    internalSelection.value = internalSelection.value.filter(
      item => getRowKey(item, 0) !== key
    )
  }
  
  emit('selection-change', internalSelection.value)
}

const handleRowClick = (row: any, index: number) => {
  emit('row-click', row, index)
}

const handlePageChange = (page: number) => {
  emit('page-change', page)
}

const handleRefresh = async () => {
  refreshing.value = true
  emit('refresh')
  // 模拟刷新延迟
  setTimeout(() => {
    refreshing.value = false
  }, 500)
}

// 监听搜索变化
watch(searchValue, (newValue) => {
  emit('search', newValue)
}, { debounce: 300 })

// 监听外部选择变化
watch(() => props.selection, (newSelection) => {
  internalSelection.value = [...newSelection]
}, { deep: true })
</script>

<style lang="scss" scoped>
.apple-table-container {
  background: var(--apple-color-background-primary);
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid var(--apple-color-separator);

  &--border {
    .apple-table {
      border-collapse: separate;
      border-spacing: 0;
    }

    .apple-table__cell {
      border-right: 1px solid var(--apple-color-separator);
      border-bottom: 1px solid var(--apple-color-separator);

      &:last-child {
        border-right: none;
      }
    }
  }
}

.apple-table__toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--apple-color-separator);
  background: var(--apple-color-background-secondary);

  &-left,
  &-right {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

.apple-table__title {
  font-size: 18px;
  font-weight: 600;
  color: var(--apple-color-text-primary);
  margin: 0;
}

.apple-table__search {
  width: 240px;
}

.apple-table__wrapper {
  overflow: auto;
  -webkit-overflow-scrolling: touch;

  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: var(--apple-color-separator);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: var(--apple-color-text-quaternary);
  }
}

.apple-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;

  &--small {
    font-size: 12px;
  }

  &--large {
    font-size: 16px;
  }
}

.apple-table__header {
  background: var(--apple-color-background-secondary);
  position: sticky;
  top: 0;
  z-index: 10;
}

.apple-table__cell {
  padding: 12px 16px;
  text-align: left;
  vertical-align: middle;
  border-bottom: 1px solid var(--apple-color-separator);
  
  &--center {
    text-align: center;
  }

  &--right {
    text-align: right;
  }

  &--selection {
    width: 48px;
    padding: 12px 16px;
  }

  &--sortable {
    cursor: pointer;
    user-select: none;

    &:hover {
      background: var(--apple-color-background-tertiary);
    }
  }

  .apple-table__header & {
    font-weight: 600;
    color: var(--apple-color-text-secondary);
    background: var(--apple-color-background-secondary);
  }

  .apple-table-container--small & {
    padding: 8px 12px;
  }

  .apple-table-container--large & {
    padding: 16px 20px;
  }
}

.apple-table__cell-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.apple-table__cell-text {
  flex: 1;
  color: var(--apple-color-text-primary);
}

.apple-table__sort-icon {
  width: 12px;
  height: 12px;
  color: var(--apple-color-text-quaternary);
  transition: all 0.2s ease;

  &--asc {
    color: var(--apple-color-accent);
    transform: rotate(0deg);
  }

  &--desc {
    color: var(--apple-color-accent);
    transform: rotate(180deg);
  }
}

.apple-table__row {
  transition: background-color 0.2s ease;

  &:hover {
    background: var(--apple-color-background-secondary);
  }

  &--selected {
    background: var(--apple-color-accent-alpha-low);
  }

  &--stripe {
    background: var(--apple-color-background-secondary);

    &:hover {
      background: var(--apple-color-background-tertiary);
    }
  }
}

.apple-table__checkbox {
  width: 16px;
  height: 16px;
  margin: 0;
  cursor: pointer;
}

.apple-table__empty,
.apple-table__loading {
  .apple-table__cell {
    padding: 48px 24px;
    text-align: center;
    border-bottom: none;
  }
}

.apple-table__empty-content,
.apple-table__loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: var(--apple-color-text-tertiary);
}

.apple-table__empty-icon,
.apple-table__loading-spinner {
  width: 48px;
  height: 48px;
  opacity: 0.5;
}

.apple-table__loading-spinner {
  border: 3px solid var(--apple-color-separator);
  border-top: 3px solid var(--apple-color-accent);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.apple-table__empty-text,
.apple-table__loading-text {
  margin: 0;
  font-size: 14px;
}

.apple-table__pagination {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-top: 1px solid var(--apple-color-separator);
  background: var(--apple-color-background-secondary);

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 12px;
  }
}

.apple-table__pagination-info {
  font-size: 14px;
  color: var(--apple-color-text-secondary);
}

.apple-table__pagination-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.apple-table__pagination-current {
  font-size: 14px;
  color: var(--apple-color-text-primary);
  min-width: 80px;
  text-align: center;
}

// 暗色模式适配
@media (prefers-color-scheme: dark) {
  .apple-table__loading-spinner {
    border-color: var(--apple-color-separator);
    border-top-color: var(--apple-color-accent);
  }
}

// 高对比度模式
@media (prefers-contrast: high) {
  .apple-table__cell {
    border-color: var(--apple-color-text-primary);
  }
}

// 减少动画模式
@media (prefers-reduced-motion: reduce) {
  .apple-table__row,
  .apple-table__sort-icon {
    transition: none;
  }

  .apple-table__loading-spinner {
    animation: none;
  }
}
</style>